<template>
    <el-select v-model="form[option.prop]" v-bind="option.element" @change="itemChange">
        <el-option v-for="item in list" :key="item.dictValue" :value="item.dictValue"
            :label="item.dictLabel"></el-option>
    </el-select>
</template>
<script setup lang="ts">
import { useDict } from './hooks';
defineOptions({ name: 'XklDictSelect' })
const props = defineProps(['form', 'option'])
const emit = defineEmits(['loaded', 'itemChange', 'update:label'])

const { form, option } = props

const dict = option.config.dict

const { list, loaded } = useDict(dict)

loaded((vals) => {
    emit('loaded', vals, (latterVals) => {
        list.value = latterVals
    })
})


const itemChange = (val) => {
    if (Array.isArray(val)) {
        const values = val
        const items = list.value.filter(res => values.includes(res.dictValue))
        const labels = items.map(res => res.dictLabel)
        if (items) {
            emit('update:label', labels)
            emit('itemChange', items)
        }
    } else {
        const item = list.value.find(res => res.dictValue === val)
        if (item) {
            emit('update:label', item.dictLabel)
            emit('itemChange', item)
        }
    }
}

</script>